package com.hsy.bibc.modules.exchange;

import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.deparse.dpframe.ui.widget.DPCircleImageView;
import com.deparse.dpframe.utils.DPGsonUtil;
import com.deparse.dpframe.utils.DPHttpUtil;
import com.deparse.dpframe.utils.DPLogUtil;
import com.hsy.bibc.R;
import com.hsy.bibc.common.Consts;
import com.hsy.bibc.modules.common.CommonBaseActivityWithSimpleActionBar;
import com.hsy.bibc.modules.exchange.GsonData.AfterExchangeCodeGsonData;
import com.hsy.bibc.modules.exchange.GsonData.ConfirmGsonData;
import com.hsy.bibc.modules.main.MainActivity;
import com.hsy.bibc.modules.common.CommitOkActivity;
import com.hsy.bibc.modules.view.ScrollExpandListView;
import com.hsy.bibc.utils.CommonUtils;
import com.hsy.bibc.utils.HttpUtil;
import com.hsy.bibc.utils.VolleyLoadPicture;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class AfterExchangeCodeActivity extends CommonBaseActivityWithSimpleActionBar {

    protected DPCircleImageView avtar;
    protected TextView nickName;
    protected TextView description;
    protected TextView orderIdTextView;
    protected TextView orderTime;
    protected ScrollExpandListView listView;
    protected TextView totalCount, finish;
    protected TextView totalScores;
    protected ScrollView scrollView;


    private GoodsListAdapter mGoodsListAdapter;


    private DPHttpUtil.HttpCallback callback = new DPHttpUtil.HttpCallback() {
        @Override
        public void onSuccess(int what, String response) {
            if (0 == what) {
                AfterExchangeCodeGsonData.Result result = DPGsonUtil.fromJson(response, AfterExchangeCodeGsonData.Result.class);
                nickName.setText(result.getUser().getNickname());
                if (isEmpty(result.getUser().getAvatar())) {

                } else {
//                    DPPicassoUtil.load(AfterExchangeCodeActivity.this, result.getUser().getAvatar(), avtar);
                    VolleyLoadPicture vlp = new VolleyLoadPicture(AfterExchangeCodeActivity.this, avtar);
                    vlp.getmImageLoader().get(result.getUser().getAvatar(), vlp.getOne_listener());
                }

                description.setText(result.getUser().getScore() + "积分");

                if (null != result.getOrder()) {
                    mGoodsListAdapter = new GoodsListAdapter(AfterExchangeCodeActivity.this, result);
                    listView.setAdapter(mGoodsListAdapter);
                    scrollView.post(new Runnable() {
                        @Override
                        public void run() {
                            scrollView.scrollTo(0, 0);
                        }
                    });
                    totalCount.setText(String.format("合计%s件", result.getOrder().getQty()));
                    totalScores.setText(result.getOrder().getAmount() + "积分");
                    totalCount.setVisibility(View.VISIBLE);
                } else {
                    totalScores.setText(result.getOrder().getAmount() + "积分");
                    totalCount.setVisibility(View.GONE);
                }
            } else if (1 == what) {
                ConfirmGsonData.Result result = DPGsonUtil.fromJson(response, ConfirmGsonData.Result.class);
                startActivity(CommitOkActivity.class, "2", result.getOrder_id(), result.getOrder_sn());

            }

            CommonUtils.hideProgressDialog();
        }

        @Override
        public void onError(int what, int type, VolleyError error) {
            CommonUtils.hideProgressDialog();
        }

        @Override
        public void onMsgError(int what, int type, String msg) {
            if (0 == what) {
                if (Consts.TYPE_CODE_ERROR == type) {
                    CommonUtils.showErrorMsgDialog(AfterExchangeCodeActivity.this, msg);
                }
            } else if (1 == what) {
                CommonUtils.hideProgressDialog();
            }


        }
    };
    private String extra;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        super.setContentView(R.layout.activity_after_exchange_code);
        setTitle(R.string.title_confirm);
        extra = getActivityStartExtra()[0];
        initView();
    }

    private void initView() {
        avtar = (DPCircleImageView) findViewById(R.id.avtar);
        nickName = (TextView) findViewById(R.id.nick_name);
        description = (TextView) findViewById(R.id.description);
        orderIdTextView = (TextView) findViewById(R.id.order_id);
        orderTime = (TextView) findViewById(R.id.order_time);
        listView = (ScrollExpandListView) findViewById(R.id.list_view);
        totalCount = (TextView) findViewById(R.id.total_count);
        totalScores = (TextView) findViewById(R.id.total_scores);
        finish = F(R.id.finish);
        scrollView = (ScrollView) findViewById(R.id.scroll_view);

        listView.setGroupIndicator(null);
        CommonUtils.showProgressDialog(this);
        Map<String, String> params = new HashMap<>();
        params.put("token", CommonUtils.getToken(this));
        params.put("code", extra);
        DPLogUtil.d("resultString==....." + extra);
        HttpUtil.httpPostWithParams(this, 0, Consts.Apis.POST_COMMIT_DH, params, callback);

        finish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CommonUtils.showProgressDialog(AfterExchangeCodeActivity.this);
                Map<String, String> params = new HashMap<>();
                params.put("token", CommonUtils.getToken(AfterExchangeCodeActivity.this));
                params.put("code", extra);
                HttpUtil.httpPostWithParams(AfterExchangeCodeActivity.this, 1, Consts.Apis.POST_CONFIRM_DH, params, callback);

            }
        });
    }


    public class GoodsListAdapter extends BaseExpandableListAdapter {
        private List<AfterExchangeCodeGsonData.Goods> listData;
        private LayoutInflater mInflater;

        public GoodsListAdapter(Context context, AfterExchangeCodeGsonData.Result src) {
            listData = src.getGoods();
            mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }

        //得到子item需要关联的数据
        @Override
        public Object getChild(int groupPosition, int childPosition) {
            return (listData.get(childPosition).getChildren());
        }

        //得到子item的ID
        @Override
        public long getChildId(int groupPosition, int childPosition) {
            return childPosition;
        }

        //设置子item的组件
        @Override
        public View getChildView(final int groupPosition, final int childPosition,
                                 boolean isLastChild, View convertView, ViewGroup parent) {
            ChildViewHolder childViewHolder = null;

            if (convertView == null) {
                convertView = mInflater.inflate(R.layout.item_confirm_order_child, null);

                childViewHolder = new ChildViewHolder();
                childViewHolder.init(convertView);
            } else {
                childViewHolder = (ChildViewHolder) convertView.getTag();
            }
            childViewHolder.setData(listData.get(groupPosition).getChildren().get(childPosition));
            return convertView;
        }

        //获取当前父item下的子item的个数
        @Override
        public int getChildrenCount(int groupPosition) {
            return listData.get(groupPosition).getChildren().size();
        }

        //获取当前父item的数据
        @Override
        public Object getGroup(int groupPosition) {
            return listData.get(groupPosition);
        }

        @Override
        public int getGroupCount() {
            return listData.size();
        }

        @Override
        public long getGroupId(int groupPosition) {
            return groupPosition;
        }

        //设置父item组件
        @Override
        public View getGroupView(int groupPosition, boolean isExpanded,
                                 View convertView, ViewGroup parent) {
            convertView = mInflater.inflate(R.layout.item_confirm_order_group, null);
            TextView firstName = (TextView) convertView.findViewById(R.id.groupName);
            firstName.setText(listData.get(groupPosition).getName());

            ImageView parentRightImage = (ImageView) convertView.findViewById(R.id.parentRightImage);
            ImageView parentLeftImage = (ImageView) convertView.findViewById(R.id.parentLeftImage);

//            DPPicassoUtil.with(AfterExchangeCodeActivity.this).load(listData.get(groupPosition).getImg()).into(parentLeftImage);
            if (isExpanded) {
                parentRightImage.setRotation(90);
            } else {
                parentRightImage.setRotation(0);
            }
            return convertView;
        }

        @Override
        public boolean hasStableIds() {
            return true;
        }

        @Override
        public boolean isChildSelectable(int groupPosition, int childPosition) {
            return true;
        }

        public class ChildViewHolder {

            public AfterExchangeCodeGsonData.Children src;

            public TextView nameTextView, score;
            public TextView priceTextView;
            public ImageView increaceImageView;
            public TextView valueEditTextExt;
            public ImageView decreaceImageView;
            public TextView unitTextView;
            public TextView showTextView;
            public LinearLayout editAreaLinearLayout;

            public ChildViewHolder() {

            }

            public void init(View convertView) {
                convertView.setTag(this);

                score = (TextView) convertView.findViewById(R.id.score);
                nameTextView = (TextView) convertView.findViewById(R.id.name);
                priceTextView = (TextView) convertView.findViewById(R.id.price);
                increaceImageView = (ImageView) convertView.findViewById(R.id.increace);
                valueEditTextExt = (TextView) convertView.findViewById(R.id.value);
                decreaceImageView = (ImageView) convertView.findViewById(R.id.decreace);
                unitTextView = (TextView) convertView.findViewById(R.id.unit);
                showTextView = (TextView) convertView.findViewById(R.id.show);
                editAreaLinearLayout = (LinearLayout) convertView.findViewById(R.id.edit_area);
            }

            public void setData(AfterExchangeCodeGsonData.Children src) {
                if (null == src) {
                    DPLogUtil.e("src = null.");
                    return;
                }
                this.src = src;
                this.nameTextView.setText(src.getName());
//                this.score.setText(src.getScore() + "积分/个");
//                this.priceTextView.setText(src.getPrice() + "元" + "/" + src.getUnit());

                this.valueEditTextExt.setText("×" + String.valueOf(src.getQty()));
//                this.showTextView.setText(String.valueOf(src.getQty()));
            }
        }
    }
}
